// pages/order/order_detail.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();

// 15分钟订单过期
const times = 15 * 60 * 1000
Page({

    /**
     * 页面的初始数据
     */
    data: {
        uid: '',

        if_show_end_paying_box: false,
        if_show_mask: false,

        order_id: '',
        status: '',
        cart_list: [],
        detail_data: {},
        options: {},

        // 订单流程的标识
        first: -1,

        // 过期标识
        timeOutFlag: false,
        // 剩余支付时间
        overplusTime: '00分钟00秒',
        goods_list: [],

        isVip: false,
        VipGrade: 0,
        discount: 1,

        number: 0,

        // 该订单发货单列表
        deliveryList: [],

        // 是否有售后记录
        isService: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        // console.log(options);
        this.init_data(options)
        await this.get_order_detail()
        await this.checkIsServicing()
        // await this.get_delivery_list()

        if (this.data.detail_data.distribution_status == 1) {
            await this.get_delivery_list()
        }
        this.isOrderTimeOut()
    },

    bottomStatus: '',
    init_data(options) {
        this.bottomStatus = options.status
        // 计算折扣
        let discount = 1
        let VipGrade = App.globalData.VipGrade
        switch (VipGrade) {
            case 1:
                discount = 0.88
                break;
            case 2:
                discount = 0.85
                break;
            case 3:
                discount = 0.8
                break;
            default:
                break;
        }

        this.setData({
            uid: App.globalData.uid,
            order_id: options.id,
            isVip: App.globalData.isVip,
            VipGrade: App.globalData.VipGrade,
            discount,
            options
        })
    },

    // 复制物流单号
    copydeliCode(e) {
        let index = e.currentTarget.dataset.index
        console.log(index);
        wx.setClipboardData({
            data: this.data.deliveryList[index]['delivery_code'],
            success: function (res) {
                wx.showToast({
                    title: '复制成功',
                    icon: 'success',
                    duration: 1500
                });
            }
        });
    },

    // 文本复制
    copytext() {
        wx.setClipboardData({
            data: this.data.detail_data.order_no,
            success: function (res) {
                wx.showToast({
                    title: '复制成功',
                    icon: 'success',
                    duration: 2000
                });
            }
        });
    },

    // 定时器变量
    timer: null,
    // 判断订单是否过期
    isOrderTimeOut() {
        let outTime = +new Date(this.data.detail_data.create_time) + times
        let Out = outTime - +new Date()
        if (Out <= 0) {
            this.setData({
                timeOutFlag: true
            })
            return
        }

        // 启动计时器 时刻判断过期
        this.timer = setInterval(() => {
            let isOut = outTime - +new Date()
            // 订单已经过期
            if (isOut <= 0) {
                clearInterval(this.timer)
                this.setData({
                    timeOutFlag: true
                })
            } else {
                let temstr = util.countDownStamp(outTime)
                this.setData({
                    overplusTime: temstr
                })
            }
        }, 1000);

    },

    // 用户不能点击切换
    // onFirstChange(e) {
    //     console.log(e.detail.current);
    //     this.setData({ first: e.detail.current });
    // },

    // 申请售后按钮回调
    askForService() {
        let oid = this.data.detail_data.id
        let order_no = this.data.detail_data.order_no
        let real_pay = this.data.detail_data.real_amount
        wx.navigateTo({
            url: `/orderPackage/ask_service?oid=${oid}&trade_num=${order_no}&real_pay=${real_pay}`
        })
    },

    // 售后详情按钮回调
    checkForService() {
        let oid = this.data.detail_data.id
        let order_no = this.data.detail_data.order_no
        let real_pay = this.data.detail_data.real_amount
        wx.navigateTo({
            url: `/orderPackage/service_status?oid=${oid}&trade_num=${order_no}&real_pay=${real_pay}`
        })
    },

    // 拨打客服电话
    callServe() {
        wx.makePhoneCall({
            phoneNumber: '13266246169', //此号码仅用于测试
            success: function () {
                console.log("拨打电话成功！")
            },
            fail: function () {
                console.log("拨打电话失败！")
            }
        })
    },

    // 获取发货单列表
    async get_delivery_list() {
        let res = await request.post(api.deliList, { order_id: this.data.order_id })// this.data.order_id 1016
        console.log('发货单列表', res);
        console.log(res);
        if (res) {
            this.setData({
                deliveryList: res,
            })
        }
    },

    // 请求判断是否有售后记录，有则只显示售后记录按钮
    async checkIsServicing() {
        let oid = this.data.detail_data.id
        let res = await request.postall(api.suggestdetail, { oid })
        if (res.code == -1) return
        // 标识为售后中，步骤条全部灰暗
        this.setData({
            isService: true,
            first: -1
        })
    },

    // 获取订单详情
    async get_order_detail() {
        let res = await request.post(api.orderdetail, { id: this.data.order_id })
        let status = res.status,
            distri = res.distribution_status,
            index
        if (status == 1) {
            index = 0
        } else if (status >= 5 && status != 10) {
            index = 4
        } else if (status == 2 && distri == 0) {
            index = 1
        } else if (status == 2 && distri == 1) {
            index = 2
        } else {
            index = -1
        }

        let number = 0
        // res.goods_array.forEach(async item => {
        //     item.goods_array = JSON.parse(item.goods_array)
        //     item.discountPrice = (item.goods_price * this.data.discount).toFixed(2)



        //     number += item.goods_nums
        // });

        // 循环中有异步操作，所以使用原生for循环
        for (let i = 0; i < res.goods_array.length; i++) {
            res.goods_array[i].goods_array = JSON.parse(res.goods_array[i].goods_array)
            res.goods_array[i].discountPrice = (res.goods_array[i].goods_price * this.data.discount).toFixed(2)
            let gooddetail = await request.post(api.goods_details, { id: res.goods_array[i].goods_id })
            let products = gooddetail.products_array
            products.forEach(pitem => {
                if (pitem.id == res.goods_array[i].product_id) {
                    res.goods_array[i].pname = pitem.name
                    return
                }
            });
            number += res.goods_array[i].goods_nums
        }

        let newlist = await this.handleCartList(res.goods_array)
        res.goods_array = newlist
        this.setData({
            detail_data: res,
            goods_list: newlist,
            first: index,
            status: res.status == 3 ? '3' : this.bottomStatus,
            number
        })
    },

    // 按照店铺排序商品
    async handleCartList(list) {
        let sellerObj = {}
        // 遍历利用店铺id，设置该店铺的商品数组，最后按顺序堆放成一个数组
        for (let i = 0; i < list.length; i++) {
            let sellerID = list[i].seller_id
            if (sellerObj[sellerID]) {
                sellerObj[sellerID].push(list[i])
            } else {
                sellerObj[sellerID] = []
                let shopDetail = await request.postall(api.shopDetail, { id: sellerID })
                if (shopDetail.code == 0) {
                    list[i].showShop = true
                    list[i].shopDetail = {}
                    list[i].shopDetail['name'] = shopDetail.data.true_name
                    list[i].shopDetail['logo'] = shopDetail.data.logo
                }
                sellerObj[sellerID].push(list[i])
            }
        }
        let newlist = []
        for (let i in sellerObj) {
            newlist.push(...sellerObj[i])
        }
        // console.log('newlist', newlist);
        return newlist
    },

    paying() {
        // 拿到订单id 继续拉起微信支付
        let post_data = {
            id: this.data.order_id,
            // 订单详情页 传递1标识为订单单独支付
            single_pay: 1
        }
        request.post(api.orderpay3, post_data).then(res => {
            this.wx_pay(res)
        })
    },

    wx_pay(res) {
        const that = this
        let post_data = res
        wx.requestPayment({
            nonceStr: post_data.nonceStr,
            package: post_data.package,
            paySign: post_data.paySign,
            timeStamp: post_data.timeStamp,
            signType: post_data.signType,
            success(res) {
                util.showSuccess('支付成功');

                wx.reLaunch({
                    url: '/pages/order/pay_success',
                })
            },
            fail(e) {
                that.go_back()
            }
        })
    },

    go_back() {
        // 待付款的订单才弹出提示框
        if (this.data.status == '1' && !this.data.timeOutFlag) {
            this.setData({
                if_show_mask: true,
                if_show_end_paying_box: true
            })
        } else {
            wx.navigateBack()
        }
    },

    continue_paying() {
        this.setData({
            if_show_end_paying_box: false,
            if_show_mask: false,
        })
    },
    stop_paying() {
        wx.navigateBack({
            delta: 1
        })
    },

    clear_mask() {
        this.setData({
            if_show_box: false,
            if_show_mask: false,
            if_show_end_paying_box: false
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.checkIsServicing()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})